package com.example.controller;

import javax.validation.Valid;
import com.example.vo.ConfigVO;
import com.firesoon.fire.dto.MultiResponse;
import com.firesoon.fire.dto.OptionDTO;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/api")
public class MultiTypeController {

    // 模拟数据存储
    private Map<String, Object> dataStore = new HashMap<>();
    private static final String UPLOAD_DIR = "uploads/";

    // 1. 简单GET请求
    @GetMapping("/hello")
    public String sayHello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }

    // 2. 路径变量GET请求
    @GetMapping("/users/{id}")
    public ResponseEntity<Object> getUser(@PathVariable String id) {
        if (dataStore.containsKey(id)) {
            return ResponseEntity.ok(dataStore.get(id));
        }
        return ResponseEntity.notFound().build();
    }

    // 3. POST请求 - 表单提交
    @PostMapping("/users")
    public ResponseEntity<Map<String, Object>> createUser(
            @RequestParam String name,
            @RequestParam int age) {
        String id = UUID.randomUUID().toString();
        Map<String, Object> user = new HashMap<>();
        user.put("id", id);
        user.put("name", name);
        user.put("age", age);

        dataStore.put(id, user);
        return ResponseEntity.ok(user);
    }

    // 4. POST请求 - JSON请求体
    @PostMapping(value = "/users/json", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> createUserWithJson(@RequestBody Map<String, Object> userData) {
        String id = UUID.randomUUID().toString();
        userData.put("id", id);
        dataStore.put(id, userData);
        return ResponseEntity.ok(userData);
    }

    // 5. 文件上传
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择文件上传");
        }

        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath);

            return ResponseEntity.ok("文件上传成功: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.ok("文件上传失败");
        }
    }

    // 6. 文件下载
    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.ok(null);
        }
    }

    // 7. PUT请求 - 更新资源
    @PutMapping("/users/{id}")
    public ResponseEntity<Object> updateUser(
            @PathVariable String id,
            @RequestBody Map<String, Object> updates) {
        if (!dataStore.containsKey(id)) {
            return ResponseEntity.notFound().build();
        }

        Map<String, Object> user = (Map<String, Object>) dataStore.get(id);
        user.putAll(updates);
        return ResponseEntity.ok(user);
    }

    // 8. DELETE请求 - 删除资源
    @DeleteMapping("/users/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable String id) {
        if (dataStore.containsKey(id)) {
            dataStore.remove(id);
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }

    // 9. 返回JSON数据的GET请求
    @GetMapping("/data")
    public Map<String, Object> getJsonData() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("code", 200);
        response.put("message", "This is a JSON response");
        response.put("data", dataStore.values());
        return response;
    }

    @GetMapping(value = "/v1/departmentOption")
    public MultiResponse<OptionDTO> departmentOption(@Valid ConfigVO configVO) {
        return MultiResponse.of(new ArrayList<>());
    }
}
